package com.spic.business.xfalarm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.spic.business.alarm.utils.DateTimeUtil;
import com.spic.business.getui.service.PushService;
import com.spic.business.hik.constant.HkConstant;
import com.spic.business.hik.utils.HkResultUtlis;
import com.spic.business.ioc.domain.IocCompliance;
import com.spic.business.xfalarm.domain.AlarmInfoDate;
import com.spic.business.xfalarm.mapper.AlarmInfoDateMapper;
import com.spic.business.xfalarm.mapper.OdsXfMapper;
import com.spic.business.xfalarm.service.IAlarmInfoDateService;
import com.spic.common.core.utils.DateUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.security.utils.DictUtils;
import com.spic.system.api.RemoteNoticeInfoService;
import com.spic.system.api.RemoteUserService;
import com.spic.system.api.domain.SysDictData;
import com.spic.system.api.domain.SysNoticeInfo;
import lombok.SneakyThrows;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.converters.SqlDateConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 290512
 * @create 2022-03-02 12:40
 */
@Service
public class AlarmInfoDateServiceImpl implements IAlarmInfoDateService
{
    private static final Logger log = LoggerFactory.getLogger(AlarmInfoDateServiceImpl.class);
    @Autowired
    private AlarmInfoDateMapper alarmInfoDateMapper;
    @Autowired
    private OdsXfMapper odsXfMapper;
    @Autowired
    private PushService doPush;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private RemoteNoticeInfoService remoteNoticeInfoService;
    @Autowired
    private ThreadPoolExecutor executor;


    @SneakyThrows
    @Override
    public void alarmInfoQueryList(String year)
    {
        //BeanUtils.populate 对象转换 时 日期处理
        ConvertUtils.register(new SqlDateConverter(null), Date.class);
        ConvertUtils.register(new Converter() {
            @Override
            public Object convert(Class type, Object value) {
                SimpleDateFormat simpleDateFormat2=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try{
                    if(value.toString().indexOf("-")!=-1){
                        return simpleDateFormat.parse(value.toString());
                    }else if(value.toString().indexOf("/")!=-1){
                        return simpleDateFormat2.parse(value.toString());
                    }else{
                        return null;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }, Date.class);

        String tableName = "AlarmInfo_" + year;
        Boolean aBoolean = selectCheckTable(tableName);
        if(aBoolean)
        {
            //  消防一
            List<AlarmInfoDate> alarmInfoDateList = new ArrayList<>();

            List<Map<String, Object>> alarmInfoYearList = alarmInfoDateMapper.getAlarmInfoDate(tableName);
            if (alarmInfoYearList != null && alarmInfoYearList.size() > 0)
            {
                for (Map<String, Object> map : alarmInfoYearList)
                {
                    AlarmInfoDate alarmInfoDate = new AlarmInfoDate();
                    BeanUtils.populate(alarmInfoDate, map);
                    String AddTime = DateTimeUtil.dateToStr(alarmInfoDate.getDAH_AddTime(), "yyyy-MM-dd HH:mm:ss");
                    String AlarmTime = DateTimeUtil.dateToStr(alarmInfoDate.getDAH_AlarmTime(), "yyyy-MM-dd HH:mm:ss");
                    alarmInfoDate.setDAH_AddTime(DateTimeUtil.strToDate(AddTime));
                    alarmInfoDate.setDAH_AlarmTime(DateTimeUtil.strToDate(AlarmTime));
                    alarmInfoDate.setYear(year);
                    alarmInfoDateList.add(alarmInfoDate);
                    Map<String,Object> alarmInfoDateXF = selectXFDatebyId(alarmInfoDate.getDAH_ID());
                    if (alarmInfoDateXF == null)
                    {
                        String fireAlarmType = DictUtils.getDictValueByTypeAndLabel(alarmInfoDate.getDAH_EventContent(), "fire_alarm_type", "0");
                        if(!"0".equals(fireAlarmType)) {
                            executor.execute(()->{
                                noticeAndOpenDoor(alarmInfoDate);
                                insertIntoXfData(alarmInfoDate);
                            });
                        }
                    }
                }
            }
        }
        Boolean aBoolean2 = selectCheckTable2(tableName);
        if(aBoolean2){
            //消防2
            List<AlarmInfoDate> alarmInfoDateList2 = new ArrayList<>();
            List<Map<String, Object>> alarmInfoYearList2 = alarmInfoDateMapper.getAlarmInfoDate2(tableName);
            if(alarmInfoYearList2!=null && alarmInfoYearList2.size()>0){
                for(Map<String, Object> map : alarmInfoYearList2){
                    AlarmInfoDate alarmInfoDate = new AlarmInfoDate();
                    BeanUtils.populate(alarmInfoDate,map);
                    String AddTime = DateTimeUtil.dateToStr(alarmInfoDate.getDAH_AddTime(), "yyyy-MM-dd HH:mm:ss");
                    String AlarmTime = DateTimeUtil.dateToStr(alarmInfoDate.getDAH_AlarmTime(), "yyyy-MM-dd HH:mm:ss");
                    alarmInfoDate.setDAH_AddTime(DateTimeUtil.strToDate(AddTime));
                    alarmInfoDate.setDAH_AlarmTime(DateTimeUtil.strToDate(AlarmTime));
                    alarmInfoDate.setYear(year);
                    alarmInfoDateList2.add(alarmInfoDate);
                    Map<String,Object> alarmInfoDateXF = selectXFDatebyId(alarmInfoDate.getDAH_ID());
                    if(alarmInfoDateXF==null){
                        String fireAlarmType = DictUtils.getDictValueByTypeAndLabel(alarmInfoDate.getDAH_EventContent(), "fire_alarm_type", "0");
                        if(!"0".equals(fireAlarmType)) {
                            executor.execute(()->{
                                noticeAndOpenDoor(alarmInfoDate);
                                insertIntoXfData(alarmInfoDate);
                            });
                        }
                    }
                }
            }
        }else{
            System.out.println("表：AlarmInfo_" + year+"不存在");
        }

    }

    public void noticeAndOpenDoor(AlarmInfoDate alarmInfoDate) {
        String dah_deviceID = alarmInfoDate.getDAH_DeviceID();
        Map<String, Object> deviceMap = odsXfMapper.selectDeviceInfoById(dah_deviceID);
        if(deviceMap != null && ! deviceMap.isEmpty()) {
            Long devicePrincipalId = (Long) deviceMap.get("devicePrincipalId");
            Long watchkeeperId = (Long) deviceMap.get("watchkeeperId");
            String accessControl = (String) deviceMap.get("accessControl");
            // 发送通知
            if(!"null".equals(String.valueOf(devicePrincipalId))) {
                this.noticeInfo((String) deviceMap.get("devtName"), devicePrincipalId+"", alarmInfoDate.getDAH_AlarmTime(), alarmInfoDate.getDAH_EventContent());
            }
            if(!"null".equals(String.valueOf(watchkeeperId))) {
                this.noticeInfo((String) deviceMap.get("devtName"), watchkeeperId+"", alarmInfoDate.getDAH_AlarmTime(), alarmInfoDate.getDAH_EventContent());
            }
            // 打开关联门禁
            if(StringUtils.isNotEmpty(accessControl)) {
                String[] split = accessControl.split(",");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("controlType", 0);
                jsonObject.put("doorIndexCodes", Arrays.asList(split));
                String result = HkResultUtlis.doPostStringArtemis(HkConstant.HK_DOOR_DOCONTROL,jsonObject.toString());
                log.info("消防告警打开门禁========"+ result);
            }
        }
    }

    /**
     * 推送消息
     */
    public void noticeInfo(String deviceName, String userId, Date date,String alertDescription){
        SysNoticeInfo info = new SysNoticeInfo();
        info.setContent("您负责的消防设备："+deviceName+"，出现告警信息："+alertDescription+"。报警时间："+ DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,date));
        info.setTitle("消防告警");
        info.setUserId(userId);
        info.setCreateBy(userId);
        info.setCreateTime(date);
        remoteNoticeInfoService.add(info);
        String cid = remoteUserService.getUserById(new Long(userId)).getData().getCid();
        Integer clientType = remoteUserService.getUserById(new Long(userId)).getData().getClientType();
        if(StringUtils.isNotEmpty(cid)){
            doPush.push(
                    cid,
                    "消防告警",
                    "您负责的消防设备："+deviceName+"，出现告警信息："+alertDescription+"。报警时间："+ DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,date)
                    ,clientType
            );
        }
    }

    public void insertIntoXfData(AlarmInfoDate alarmInfoDate){
        try
        {
            int i = odsXfMapper.insertAlarmInfoDate(alarmInfoDate);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public Map<String,Object> selectXFDatebyId(String id){
        Map<String,Object>  map = odsXfMapper.selectAlarmInfoDateById(id);
        return  map;

    }

    public Boolean selectCheckTable(String table){
        Boolean flag = true;
        List<String> tableList = alarmInfoDateMapper.getAlarmInfoDateCheckTable();
        if(tableList!=null && tableList.size()>0){
            for (String tblNname : tableList)
            {
                if(table.equals(tblNname)){
                    flag=  true;
                    break;
                }else{
                    flag=  false;
                }
            }
        }
        return flag;
    }
    public Boolean selectCheckTable2(String table){
        Boolean flag = true;
        List<String> tableList = alarmInfoDateMapper.getAlarmInfoDateCheckTable2();
        if(tableList!=null && tableList.size()>0){
            for (String tblNname : tableList)
            {
                if(table.equals(tblNname)){
                    flag=  true;
                    break;
                }else{
                    flag=  false;
                }
            }
        }
        return flag;
    }
}
